package com.example.teach.service.impl;

import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class InMemoryChatMemoryImpl implements ChatMemory {

    // 使用ConcurrentHashMap确保线程安全
    private final Map<String, List<Message>> conversationHistories = new ConcurrentHashMap<>();

    @Override
    public void add(String conversationId, List<Message> messages) {
        conversationHistories.computeIfAbsent(conversationId, k -> new ArrayList<>())
                .addAll(messages);
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        List<Message> history = conversationHistories.getOrDefault(conversationId, Collections.emptyList());
        int startIndex = Math.max(0, history.size() - lastN);
        return history.subList(startIndex, history.size());
    }

    @Override
    public void clear(String conversationId) {
        conversationHistories.remove(conversationId);
    }
}
